<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="tabs">
      <div
        class="tabs-item"
        :class="{ active: currentTab === index }"
        v-for="(item, index) of tabs"
        :key="index"
        @click="handleChangeTab(item, index)"
      >
        {{ item.name }}
        {{ item.total !== null ? `（${item.total}）` : '' }}
      </div>
    </div>
    <div class="body">
      <BaseInfo
        ref="baseInfoRef"
        :type="type"
        :detailInfo="baseInfo"
        :status="status"
        v-show="currentTab === 0"
      />
      <TabForm
        ref="tabFormRef"
        :type="type"
        :projectId="projectId"
        :pkid="pkid"
        :topType="tabs[currentTab].name"
        :status="status"
        v-if="currentTab !== 0"
        @updateCount="getCounts"
      />
    </div>
    <div class="check">
      <div class="info">
        <el-button
          :disabled="!checkList.length"
          @click="viewCheckInfo"
          class="save-btn"
          >审核记录</el-button
        >
        <div class="check-result" v-if="checkList.length">
          <span
            >审核时间: {{ newCheckInfo.checkTime }}</span
          >
          <span class="divide-line"></span>
          <span
            >审核结果:
            <span
              :style="{
                color:
                  newCheckInfo.checkStatus === '1'
                    ? '#00CA6D'
                    : '#F9801C'
              }"
              >{{
                newCheckInfo.checkStatus === '1'
                  ? '审核通过'
                  : '退回'
              }}</span
            ></span
          >
          <div class="divide-line"></div>
          <span>审核意见: {{ newCheckInfo.content }}</span>
        </div>
      </div>
      <div
        class="info"
        v-show="type === 'edit' || type === 'change'"
      >
        <el-button
          @click="saveInfo(false)"
          class="save1-btn"
          :loading="btnLoding"
          >保存</el-button
        >
        <el-button
          @click="saveInfo(true)"
          class="save-btn"
          :loading="btnLoding"
          >提交</el-button
        >
      </div>
      <el-button
        v-show="showCheck"
        @click="handleCheck"
        class="save-btn"
        :loading="btnLoding"
        >审核</el-button
      >
    </div>

    <!-- 审核弹窗 -->
    <checkDialog
      ref="checkRef"
      @success="handleCheckOver"
    />
    <!-- 审核记录 -->
    <shenheHistory
      ref="checkInfoRef"
      dept="departName"
      :user="configUN"
      opinion="content"
      passKey="1"
      status="checkStatus"
      :data="checkList"
    />
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import BaseInfo from './components/baseInfo.vue'
import TabForm from './components/tabForm.vue'
import checkDialog from './components/checkDialog.vue'
import shenheHistory from '@/components/checkHistory/shenheHistory.vue'
import {
  addProjectInfo,
  queryProjectDetail,
  queryCheckList,
  queryCounts
} from '@/api/reportManagement'
import { getDictOptions } from '@/utils/dict'
import {
  isAdmin,
  isEnterprise,
  isJldw,
  isSgdw,
  isJcdw
} from '@/utils/permission'

export default {
  props: {
    dataStr: String,
    projectId: String,
    pkid: String,
    title: String,
    type: String
  },
  components: {
    Breadcrumb,
    BaseInfo,
    TabForm,
    checkDialog,
    shenheHistory
  },
  data() {
    return {
      tabs: [
        {
          name: '工程概括',
          total: null
        }
      ],
      currentTab: 0,
      loading: false,
      btnLoding: false,
      baseInfo: {},
      status: '0',

      checkList: [],
      newCheckInfo: {},
      configUN: 'userName'
    }
  },
  watch: {
    dataStr: {
      handler(newVal) {
        if (newVal) {
          const data = JSON.parse(newVal)
          if (data.projectId) {
            this.baseInfo = Object.assign(
              this.baseInfo,
              data
            )
          }
        }
      },
      immediate: true
    }
  },
  computed: {
    showCheck() {
      if (
        this.type === 'check' &&
        ((this.status === '3' && isJldw()) ||
          (this.status === '4' && isEnterprise()))
      ) {
        return true
      } else {
        return false
      }
    },
    titles() {
      return [this.title]
    }
  },
  mounted() {
    this.initOptions()
    if (this.pkid) {
      this.getDetailInfo()
      this.getCheckList()
    }
  },
  methods: {
    async initOptions() {
      const data = await getDictOptions(
        'zhjs_aq_problem_type'
      )
      const arr = []
      data.forEach((element) => {
        arr.push({
          name: element.dictValue,
          total: 0
        })
      })
      this.tabs = this.tabs.concat(arr)
      this.getCounts()
    },
    // 切换tab
    handleChangeTab(item, index) {
      if (index !== 0 && !this.pkid) {
        this.$message.warning('请先保存工程概括信息')
        return
      }
      this.currentTab = index
      this.$nextTick(() => {
        this.$refs.tabFormRef.init(this.tabs[index].name)
      })
    },

    // 获取项目详情
    getDetailInfo() {
      this.loading = true
      queryProjectDetail(this.pkid).then((res) => {
        if (res.success) {
          this.baseInfo = res.data
          this.status = res.data.status
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },

    // 点击保存
    saveInfo(isSubmit) {
      this.$refs.baseInfoRef.$refs.basicFormRef.validate(
        (res) => {
          if (res) {
            this.btnLoading = true
            let formData = JSON.parse(
              JSON.stringify(
                this.$refs.baseInfoRef.basicForm
              )
            )
            /**
             * 0：待提交、2：待整改、3：待初审、4：待审核、-1：退回修改、1：审核通过
             * 提交：
             * 第一次 || 待提交 => 待整改
             * 待整改 || 审核退回 => 待初审
             * 其余状态不变
             *
             * 保存
             * 第一次 => 待提交
             * 其余状态不变
             */
            if (isSubmit) {
              if (
                !formData.pkid ||
                formData.status === '0'
              ) {
                formData.status = '2'
              } else if (
                formData.status === '2' ||
                formData.status === '-1'
              ) {
                formData.status = '3'
              }
            } else {
              if (!formData.pkid) {
                formData.status = '0'
              }
            }

            addProjectInfo(formData).then((res) => {
              if (res.success) {
                this.$message.success('保存成功')
                if (!formData.pkid || isSubmit) {
                  this.$router.push(
                    '/wisdomConstruction/reportManagement/list'
                  )
                }
              } else {
                this.$message.error(res.message)
              }
              this.btnLoading = false
            })
          }
        }
      )
    },

    // 总数
    getCounts() {
      queryCounts({ refId: this.pkid }).then((res) => {
        res.data.forEach((item) => {
          this.tabs.forEach((tab) => {
            if (item.topType === tab.name) {
              tab.total = item.total
            }
          })
        })
      })
    },

    // 获取审核记录
    getCheckList() {
      queryCheckList({ refId: this.pkid }).then((res) => {
        this.checkList = res.data
        this.newCheckInfo = res.data[0]
      })
    },

    // 查看审核记录
    viewCheckInfo() {
      // this.headerTitle = '审核记录'
      this.$nextTick(() => {
        this.$refs.checkInfoRef.openDialog()
      })
    },

    // 审核
    handleCheck() {
      this.$refs.checkRef.show(
        this.pkid,
        this.status,
        false
      )
    },

    // 审核完成
    handleCheckOver() {
      this.$router.push(
        '/wisdomConstruction/reportManagement/list'
      )
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .tabs {
    width: 100%;
    height: 50px;
    border-bottom: 1px solid #f1f1f1;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    &-item {
      display: flex;
      align-items: center;
      justify-content: center;
      // min-width: 150px;
      height: 100%;
      font-size: 16px;
      font-weight: 500;
      color: #4c565c;
      position: relative;
      box-sizing: border-box;
      padding: 0 20px;
      cursor: pointer;
      &::before {
        position: absolute;
        content: ' ';
        right: 0;
        top: 19px;
        width: 1px;
        height: 12px;
        background: #d0d8e1;
      }
      &:last-child {
        &::before {
          display: none;
        }
      }
      &.active {
        color: #497fa3;
        &::after {
          position: absolute;
          content: ' ';
          bottom: 0;
          left: 50%;
          width: 26px;
          height: 3px;
          background: #497fa3;
          border-radius: 2px;
          transform: translate(-50%, -50%);
        }
      }
    }
  }
}

.check {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 78px;
  background: #fff;
  border-top: 1px solid #f1f1f1;
  box-sizing: border-box;
  padding: 0 30px;
}

.info {
  display: flex;
}

.check-result {
  margin-left: 30px;
  font-size: 14px;
  display: flex;
  align-items: center;

  .divide-line {
    margin: 0 20px;
    width: 1px;
    height: 12px;
    background: #d0d8e1;
    border-radius: 1px;
  }
}
</style>
